#include "hal_led.h"
#include "hk32c030xx_gpio.h"
#include "hk32c030xx_flash.h"
#include "hal_tty.h"

#define BOOT0_SEL_REG	0x1FFFF838
#define FLASH_OPT_REG_BASE	OB_BASE

static void boot0_sw_gpio() {

	uint32_t mdata[16];
	uint8_t i;
	uint32_t Address_OPT = 0x1FFFF804;	

	if(((*(uint32_t *)0x1FFFF838 & 0x0000ffff) == 0x00000adbc) && 
			(*(uint32_t*)0x1FFFF800 & 0xff7fffff) == 0)
		return ;
	
	for(i = 0;i < 16;i++) {
		mdata[i]=*(__IO uint32_t*)Address_OPT;
		Address_OPT += 4;
	}

	mdata[13] &= 0xFFFF0000;
	mdata[13] |= 0x0000ADBC;
	
	FLASH_Unlock();
	FLASH_OBUnlock();
	FLASH_OBErase();
	
	Address_OPT = 0x1FFFF804;
	for(i = 0;i < 16;i++) {
		FLASH_OBProgramData(Address_OPT,mdata[i]);//自动取反 
		Address_OPT += 4;		
	}
	
	Address_OPT = 0x1FFFF800;
	mdata[0] = *(__IO uint32_t*)Address_OPT;
	mdata[0] &= 0xff7fffff;	
	FLASH_OBProgramData(0x1FFFF800,mdata[0]);	//自动取反 

	FLASH_OBLock();
	FLASH_Lock();
}

/**
 * @brief 电源灯初始化
 ***/
static void power_led_init() {

	GPIO_InitTypeDef sys_led;
	RCC_AHBPeriphClockCmd(LED_POWER_CORE, ENABLE);
	
    sys_led.GPIO_Pin = LED_POWER_PIN;
    sys_led.GPIO_Mode = GPIO_Mode_OUT;
    sys_led.GPIO_OType = GPIO_OType_PP;
    sys_led.GPIO_Speed = GPIO_Speed_50MHz;
    sys_led.GPIO_PuPd = GPIO_PuPd_NOPULL;
    sys_led.GPIO_Schmit = GPIO_Schmit_Disable;
    GPIO_Init(LED_POWER_BASE, &sys_led);
	
#if BOOT0_SYS_LED
	boot0_sw_gpio();
#endif
}

/**
 * @brief 电源灯输出
 ***/
static void power_led_output(int output) {
    GPIO_WriteBit(LED_POWER_BASE,LED_POWER_PIN,output);
}

/**
 * @brief 电源灯反转
 ***/
static void power_led_toggle() {
    GPIO_Toggle(LED_POWER_BASE,LED_POWER_PIN);
}

/**
 * @brief 电源灯注销
 ***/
static void power_led_uninit() {
    GPIO_DeInit(LED_POWER_BASE);
}

/**
 * @brief 电源灯初始化
 ***/
const power_led_t g_power_led_ = {
    power_led_init,
    power_led_output,
    power_led_toggle,
    power_led_uninit
};
